//
//  TopicListViewController.m
//  AgriMobile
//
//  Created by 春名 啓作 on 11/06/02.
//  Copyright 2011 e-agri. All rights reserved.
//

#import "TopicListViewController.h"

#define C_title		0
#define C_url		1
#define C_date		2
#define C_body		3
#define C_images	4

@implementation TopicListViewController

@synthesize topicListUrl;
@synthesize topicListImgUrl;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	NSLog(@"TopicListViewController - viewDidLoad");

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (IBAction)addNewTopic:(id)sender {
	PostViewController *postView = [[PostViewController alloc] initWithNibName:@"PostViewController" bundle:nil];
	postView.title = self.title;
	postView.topicId = self.topicListUrl;
	[super.navigationController pushViewController:postView animated:YES];
	[postView release];
}

- (void)viewWillAppear:(BOOL)animated {
	
	NSLog(@"TopicListViewController - viewWillAppear, topicListUrl = %@", topicListUrl);

	if ([topicListUrl rangeOfString:@"a=page_h_message_box"].location == NSNotFound) {

		//button with caption
		NSString* btnCaption = @"トピック";
		if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]){
			btnCaption = @"日記を書く";
		}else if ([topicListUrl rangeOfString:@"a=page_f_home"].location != NSNotFound){
			btnCaption = @"メッセージ";
		}
	
		UIBarButtonItem *button = [[[UIBarButtonItem alloc]
								initWithTitle:btnCaption
								style:UIBarButtonItemStyleBordered
								target:self
								action:@selector(addNewTopic:)] retain];
		self.navigationItem.rightBarButtonItem = button;
		[button release];
	}
	
	SharedDictionary *sd = [SharedDictionary sharedDictionary];
	if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]){
		topicData = [[[sd.data objectForKey:@"diary"] objectForKey:@"data"] retain];
	}else{
		//reloadData
		NSString *urlstr = [NSString stringWithFormat:@"%@/wap?%@", URLRoot, topicListUrl];
		NSDictionary *map = [[[[[HttpMethod alloc] autorelease] doGet:urlstr] JSONValue] retain];
		topicData = [[map objectForKey:@"data"] retain];
		[map release];
	}

	NSLog(@"topicData = %@", topicData);
	[self.tableView reloadData];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger) section {

	switch (section) {
		case 0:return @"";
		case 1:
			if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]) {
				return @"";
			} else if ([topicListUrl rangeOfString:@"a=page_h_message_box"].location != NSNotFound) {
				return @"メッセージ";
			}else{
				return @"トピック";
			}
		default:
			return nil;
	}

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	
	switch (section) {
		case 0:
			if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]
			|| [topicListUrl rangeOfString:@"a=page_e_diary_list"].length > 0) {
				return 0;
			}else{
				return 2;
			}
		case 1:
			if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]) {
				return [topicData count] + 1;
			} else {
				return [topicData count];
			}
		default:
			return 0;
	}
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //static NSString *CellIdentifier = @"Cell";
	NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d-%d", indexPath.section, indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	//NSLog(@"in section %d row %d", indexPath.section, indexPath.row);
	
	cell.textLabel.font = [UIFont systemFontOfSize:12.0];
	//cell.detailTextLabel.textColor = [UIColor blackColor];
	
	if (indexPath.section == 0) {

		switch (indexPath.row) {
			case 0:
				cell.textLabel.text = self.title;
				if (topicListImgUrl != nil) {

					NSData* imgData = nil;
					UIImage* img = nil;
					
					SharedDictionary *sd = [SharedDictionary sharedDictionary];
					if ([sd.data objectForKey:@"img"] == nil) {
						[sd.data setObject:[NSMutableDictionary dictionary] forKey:@"img"];
					}
					NSMutableDictionary *imgCache = [sd.data objectForKey:@"img"];
					
					if([imgCache objectForKey:topicListImgUrl] == nil){
						NSString *imgUrl = [NSString stringWithFormat:@"%@",topicListImgUrl];
						imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
						img = [[[UIImage alloc] initWithData:imgData] retain];
						
						if(img != nil){
							[imgCache setObject:img forKey:topicListImgUrl];
							[sd.data setObject:imgCache forKey:@"img"];
						}
					}else{
						img = [[imgCache objectForKey:topicListImgUrl] retain];
					}
					
					cell.imageView.image = img;
					[img release];
				}
				
				if ([topicListUrl rangeOfString:@"a=page_h_message_box"].location != NSNotFound) {
					cell.textLabel.text = @"受信メッセージ";
				}
				
				break;
			case 1:

				if ([topicListUrl rangeOfString:@"a=page_h_message_box"].location != NSNotFound) {
					cell.textLabel.text = @"送信済メッセージ";
				}else if ([topicListUrl rangeOfString:@"a=page_f_home&"].location != NSNotFound) {
						cell.textLabel.text = @"アルバムを見る";
						cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				}else {
					cell.textLabel.text = @"";
				}

				break;
			default:
				cell.textLabel.text = [NSString stringWithFormat:@"%d - %d", indexPath.section, indexPath.row];
		}

	}else{
		if (indexPath.row == 0
		&& [topicListUrl isEqualToString:@"a=page_fh_diary_list"]) {

				cell.detailTextLabel.text = @"▼スライドで更新▼";
		}else{
			int topicIndex = indexPath.row;

			if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]) {
				topicIndex = indexPath.row - 1;
			}
			
			NSArray *oneTopic = [topicData objectAtIndex:topicIndex];

			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", 
				[oneTopic objectAtIndex:C_date],
				[oneTopic objectAtIndex:C_title]];
			cell.detailTextLabel.text = [oneTopic objectAtIndex:C_body];
			cell.imageView.image = nil;

			if([[oneTopic objectAtIndex:C_images] count] > 0){
				NSString* imgName = [oneTopic objectAtIndex:C_images];
				NSData* imgData = nil;
				UIImage* img = nil;
				
				SharedDictionary *sd = [SharedDictionary sharedDictionary];
				if ([sd.data objectForKey:@"img"] == nil) {
					[sd.data setObject:[NSMutableDictionary dictionary] forKey:@"img"];
				}
				NSMutableDictionary *imgCache = [sd.data objectForKey:@"img"];

				if([imgCache objectForKey:imgName] == nil){
					NSString *imgUrl = [NSString stringWithFormat:@"%@",[[oneTopic objectAtIndex:C_images] objectAtIndex:0]];
					//NSLog(@"imgUrl = %@", imgUrl);
					
					imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
					img = [[[UIImage alloc] initWithData:imgData] retain];
					
					if(img != nil){
						[imgCache setObject:img forKey:imgName];
						[sd.data setObject:imgCache forKey:@"img"];
					}
				}else{
					img = [[imgCache objectForKey:imgName] retain];
				}
				cell.imageView.image = img;
				[img release];
			}
		}
	}

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	//topicListUrl = @"a=page_h_message_box&box=inbox";

	switch (indexPath.section) {
		case 0:
			if ([topicListUrl rangeOfString:@"a=page_h_message_box"].location != NSNotFound) {
				switch (indexPath.row) {
					case 0:
						topicListUrl = @"a=page_h_message_box&box=inbox";
						self.title = @"受信メッセージ";
						break;

					case 1:
						topicListUrl = @"a=page_h_message_box&box=outbox";
						self.title = @"送信済みメッセージ";
						break;
				}
				
				[self viewWillAppear:YES];
			}else if (indexPath.row == 1
				&& [topicListUrl rangeOfString:@"a=page_f_home&"].location != NSNotFound) {
				
				NSString* actionId = [NSString stringWithFormat:@"a=page_fh_album_list&%@",
									[topicListUrl substringFromIndex:[topicListUrl rangeOfString:@"target_c_member_id="].location]];
				NSLog(@"actionId = %@", actionId);
				
				FriendComViewController* viewCon = [[[FriendComViewController alloc] initWithNibName:@"FriendComView" bundle:nil] retain];
				((FriendComViewController*)viewCon).actionId = actionId;
				viewCon.title = @"アルバム";
				[super.navigationController pushViewController:viewCon animated:YES];
				[viewCon release];
			}
			break;
		case 1:
			if ([topicData count] > 0) {
				
				int topicIndex = indexPath.row;
				
				if ([topicListUrl isEqualToString:@"a=page_fh_diary_list"]) {
					
					topicIndex = indexPath.row - 1;
				}
				
				if (topicIndex >= 0) {
					
					NSRange rng = [[[topicData objectAtIndex:topicIndex] objectAtIndex:C_url] rangeOfString:@"a=page_e_diary_list&"];
					NSLog(@"rng.length = %d", rng.length);
					if (rng.length > 0) {
						TopicListViewController *topicListViewController = [[TopicListViewController alloc] initWithNibName:@"TopicListView" bundle:nil];
						topicListViewController.topicListUrl = [[topicData objectAtIndex:topicIndex] objectAtIndex:C_url];
						[self.navigationController pushViewController:topicListViewController animated:YES];
						[topicListViewController release];
					}else {
						TopicViewController *topicViewController = [[TopicViewController alloc] initWithNibName:@"TopicView" bundle:nil];
						topicViewController.topicId = [[topicData objectAtIndex:topicIndex] objectAtIndex:C_url];
						topicViewController.parentId = self.topicListUrl;
						[self.navigationController pushViewController:topicViewController animated:YES];
						[topicViewController release];
					}
				}
			}
			break;
		default:
			break;
	}
	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

